import React, { createContext, useContext, useReducer, useEffect, ReactNode } from 'react';
import { hydrateAgentPrompts } from '../lib/prompt-loader';

// 配置状态类型定义
interface ConfigState {
  apiKey: string;
  modelOverride: string;
  agentConfig: any;
  workflow: any;
  isLoading: boolean;
  error: string | null;
}

// 配置动作类型
type ConfigAction = 
  | { type: 'SET_API_KEY'; payload: string }
  | { type: 'SET_MODEL_OVERRIDE'; payload: string }
  | { type: 'SET_AGENT_CONFIG'; payload: any }
  | { type: 'SET_WORKFLOW'; payload: any }
  | { type: 'SET_LOADING'; payload: boolean }
  | { type: 'SET_ERROR'; payload: string | null }
  | { type: 'RESET_CONFIG' };

// 初始状态
const initialState: ConfigState = {
  apiKey: '',
  modelOverride: '',
  agentConfig: null,
  workflow: null,
  isLoading: true,
  error: null,
};

// Reducer函数
function configReducer(state: ConfigState, action: ConfigAction): ConfigState {
  switch (action.type) {
    case 'SET_API_KEY':
      return { ...state, apiKey: action.payload };
    case 'SET_MODEL_OVERRIDE':
      return { ...state, modelOverride: action.payload };
    case 'SET_AGENT_CONFIG':
      return { ...state, agentConfig: action.payload };
    case 'SET_WORKFLOW':
      return { ...state, workflow: action.payload };
    case 'SET_LOADING':
      return { ...state, isLoading: action.payload };
    case 'SET_ERROR':
      return { ...state, error: action.payload };
    case 'RESET_CONFIG':
      return initialState;
    default:
      return state;
  }
}

// Context类型
interface ConfigContextType {
  state: ConfigState;
  dispatch: React.Dispatch<ConfigAction>;
  // 便捷方法
  setApiKey: (apiKey: string) => void;
  setModelOverride: (model: string) => void;
  setAgentConfig: (config: any) => void;
  setWorkflow: (workflow: any) => void;
  setLoading: (loading: boolean) => void;
  setError: (error: string | null) => void;
  resetConfig: () => void;
  // 计算属性
  isConfigured: () => boolean;
  hasMCPEnabled: () => boolean;
  saveToStorage: () => Promise<void>;
  loadFromStorage: () => Promise<void>;
}

// 创建Context
const ConfigContext = createContext<ConfigContextType | undefined>(undefined);

// Provider组件
interface ConfigProviderProps {
  children: ReactNode;
}

export function ConfigProvider({ children }: ConfigProviderProps) {
  const [state, dispatch] = useReducer(configReducer, initialState);

  // 便捷方法
  const setApiKey = (apiKey: string) => {
    dispatch({ type: 'SET_API_KEY', payload: apiKey });
  };

  const setModelOverride = (model: string) => {
    dispatch({ type: 'SET_MODEL_OVERRIDE', payload: model });
  };

  const setAgentConfig = (config: any) => {
    dispatch({ type: 'SET_AGENT_CONFIG', payload: config });
  };

  const setWorkflow = (workflow: any) => {
    dispatch({ type: 'SET_WORKFLOW', payload: workflow });
  };

  const setLoading = (loading: boolean) => {
    dispatch({ type: 'SET_LOADING', payload: loading });
  };

  const setError = (error: string | null) => {
    dispatch({ type: 'SET_ERROR', payload: error });
  };

  const resetConfig = () => {
    dispatch({ type: 'RESET_CONFIG' });
  };

  // 计算属性
  const isConfigured = () => {
    return Boolean(state.apiKey && state.apiKey.trim());
  };

  const hasMCPEnabled = () => {
    return Boolean(state.agentConfig?.mcp?.enabled);
  };

  // 存储操作
  const saveToStorage = async () => {
    try {
      await chrome.storage.local.set({
        openrouterConfig: {
          apiKey: state.apiKey,
          model: state.modelOverride,
        }
      });
    } catch (error) {
      console.error('保存配置失败:', error);
    }
  };

  const loadFromStorage = async () => {
    try {
      const defaults = {
        openrouterConfig: {
          apiKey: '',
          model: ''
        }
      };
      const { openrouterConfig } = await chrome.storage.local.get(defaults);
      setApiKey(openrouterConfig.apiKey || '');
      setModelOverride(openrouterConfig.model || '');
    } catch (error) {
      console.error('加载配置失败:', error);
      setError('加载配置失败');
    }
  };

  // 加载Agent配置
  useEffect(() => {
    const loadAgentConfig = async () => {
      try {
        setLoading(true);
        const response = await fetch(chrome.runtime.getURL('agents-config.json'));
        const rawConfig = await response.json();
        const agentConfig = await hydrateAgentPrompts(rawConfig);
        setAgentConfig(agentConfig);
        setWorkflow(agentConfig.workflow || {});
        setError(null);
      } catch (error) {
        console.error('加载 Agent 配置失败:', error);
        setError('加载 Agent 配置失败，请检查扩展资源。');
      } finally {
        setLoading(false);
      }
    };

    loadAgentConfig();
  }, []);

  const contextValue: ConfigContextType = {
    state,
    dispatch,
    setApiKey,
    setModelOverride,
    setAgentConfig,
    setWorkflow,
    setLoading,
    setError,
    resetConfig,
    isConfigured,
    hasMCPEnabled,
    saveToStorage,
    loadFromStorage,
  };

  return (
    <ConfigContext.Provider value={contextValue}>
      {children}
    </ConfigContext.Provider>
  );
}

// Hook
export function useConfig() {
  const context = useContext(ConfigContext);
  if (context === undefined) {
    throw new Error('useConfig must be used within a ConfigProvider');
  }
  return context;
}

// 便捷Hook
export function useConfigStatus() {
  const { state, isConfigured, hasMCPEnabled } = useConfig();
  
  return {
    ...state,
    isConfigured: isConfigured(),
    hasMCPEnabled: hasMCPEnabled(),
  };
}
